package com.hu.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hu.common.common.HttpStatus;
import com.hu.common.exception.ServiceException;
import com.hu.common.pojo.Menu;
import com.hu.common.pojo.User;
import com.hu.common.pojo.dto.UserDTO;
import com.hu.user.mapper.RoleMenuMapper;
import com.hu.user.mapper.RoleMapper;
import com.hu.user.mapper.UserMapper;
import com.hu.user.service.IMenuService;
import com.hu.user.service.IUserService;
import com.hu.user.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hu
 * @since 2023-07-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private static final Log LOG = Log.get();



    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private IUserService userService;

    @Resource
    private IMenuService menuService;

    @Resource
    private UserMapper userMapper;

    /**
     * 根据username判断该用户名是否被占用
     * @param username
     * @return
     */
    @Override
    public Boolean isRegister(String username) {
        User user = userMapper.isRegister(username);
        // 如果没有查到，isRegister的值就是false，则可以进行下一步操作
        if (user == null) {
            return false;
        }else {
            return true;
        }
    }

    @Override
    public UserDTO login(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        // 如果能拿到one，就是我们自己的业务异常
        if (one != null) {
            // 从one拷贝属性至userDTO
            BeanUtil.copyProperties(one, userDTO, true);
            // 设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);

            // 获取用户的角色信息 user表中的role就是role表中的flag： admin、user...
            String role = one.getRole();
            // 根据该角色的role查询菜单列表
            List<Menu> roleMenus = getRoleMenus(role);
            userDTO.setMenus(roleMenus);
            return userDTO;
        }else {
            throw new ServiceException(HttpStatus.USER_ERROR, "用户名或密码错误");
        }
    }

    // 注册完成后把整个user对象返回
    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one == null) {
            one = new User();
            // 把userDTO的属性拷贝到one
            BeanUtil.copyProperties(userDTO, one,true);
            save(one);
        }else {
            throw new ServiceException(HttpStatus.USER_ERROR, "用户已存在");
        }
        return one;
    }

    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        queryWrapper.eq("password",userDTO.getPassword());
        User one;
        // 先拿one，如果从数据库拿不到one，就是系统错误
        try {
            one = getOne(queryWrapper);
        }catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(HttpStatus.ERROR, "系统错误");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     * @param roleFlag: 当前角色的roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag) {
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        String menuIds = roleMenuMapper.selectMenuByRoleId(roleId);
        List<Integer> ids;
        if (StringUtils.isEmpty(menuIds)) {
            return null;
        }
        // 把前端传过来的menuIds转成数组
        List<String> split= Arrays.asList(menuIds.split(","));
        // 将字符串元素转化成int
        ids = split.stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());

        // 查出所有菜单
        List<Menu> menus = menuService.findMenus("");

        // 准备一个最后筛选完成之后的list
        ArrayList<Menu> roleMenus = new ArrayList<>();

        // 遍历所有菜单，再筛选当前用户的菜单
        for (Menu menu: menus) {
            // 用户传来的菜单数组，如果是一级菜单id，先不管子菜单的问题，给他一股脑全塞进去roleMenus
            if (ids.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            // 然后再来一次循环，把多余的子菜单删除掉
            List<Menu> children = menu.getChildren();
            children.removeIf(child -> !ids.contains(child.getId()));
        }
        return roleMenus;
    }

    public List<User> getAllUserList() {
        return userMapper.getAllUser();
    }

    @Override
    public List<User> queryProperty(User user, Integer orderStatus, String columnName) {
        if (StringUtils.isEmpty(columnName)) {
            columnName = "id";
        }
        return userMapper.queryProperty(user, orderStatus, columnName);
    }
}

